<template>
	<view class="edit">
		<view class="title">
			<input type="text" v-model="artObj.title" placeholder="请输入完整的标题" placeholder-class="placeholderClass">
		</view>
		<view class="content">
			<!-- @input="ipt" -->
			<editor class="myEdit" placeholder="写点什么吧~~" @ready="onEditorReady" @statuschange="onStatusChange"
				@focus="onFocus" @input="ipt" show-img-size show-img-toolbar show-img-resize></editor>
		</view>
		<view class="btnGroup">
			<u-button type="primary" text="确认发布" @click="onSubmit" :disabled="isDisabled"></u-button>
			<!-- <u-button type="primary" text="确认修改" @click="updateData" :disabled="isDisabled"></u-button> -->
		</view>
		<view class="tools" @click="format" v-if="toolShow">
			<view class="item"><text :class="formats.header === 2 ? 'toolsactive' : ''" class="iconfont icon-zitibiaoti"
					data-name="header" :data-value="2"></text></view>
			<view class="item"><text :class="formats.bold ? 'toolsactive' : ''" class="iconfont icon-zitijiacu"
					data-name="bold"></text></view>
			<view class="item"><text :class="formats.italic ? 'toolsactive' : ''" class="iconfont icon-zitixieti"
					data-name="italic"></text></view>
			<view class="item" @click="insertDivider"><text class="iconfont icon-fengexian"></text> </view>
			<view class="item" @click="selectImage"><text class="iconfont icon-charutupian"></text></view>
			<view class="item" @click="editOk"><text class="iconfont icon-duigou_kuai"></text></view>
		</view>
	</view>
</template>

<script>
	import {
		getImgSrc,
		getProvince
	} from "@/utils/tools.js"
	const cObj = uniCloud.importObject("CloudFishCircle-cObj", {
		loadingOptions: { // loading相关配置
			title: '上传中...', // 显示的loading内的提示文字。默认值为：加载中...
			mask: true // 是否使用透明遮罩，配置为true时不可点击页面其他内容。默认值为：true
		},
	})
	const db = uniCloud.database()
	export default {
		data() {
			return {
				toolShow: false,
				formats: {},
				tempFiles: [],
				artObj: {
					title: "",
					content: "",
					description: "",
					picurls: "",
					province: ""
				},
				methodName: "",
			};
		},
		computed: {
			isDisabled() {
				let flag = !(this.artObj.title.trim().length && this.artObj.content.trim().length)
				return flag
			}
		},
		onLoad(e) {
			// console.log(e);
			this.methodName = e.metN
			this.articleID = e.actID
			getProvince().then(res => {
				this.artObj.province = res
			})
		},
		mounted() {
			if (this.methodName === 'update') {
				this.$nextTick(function() {
					const eventChannel = this.getOpenerEventChannel();
					// 监听acceptDataFromOpenerPage事件，获取上一页面通过eventChannel传送到当前页面的数据
					eventChannel.on('acceptDataFromOpenerPage', ({
						data
					}) => {
						// console.log(data)
						this.artObj.title = data.title
						this.artObj.content = data.content
						this.artObj.picurls = data.picurls
						try {
							this.editorCtx.setContents({
								html: data.content
							})
						} catch (e) {
							uni.showToast({
								title: "出错了",
								icon: "none"
							})
							setTimeout(() => {
								uni.reLaunch({
									url: "/pages/index/index"
								})
							}, 800)
						}

					})
				})
			}
		},
		methods: {
			updateData() {
				this.editorCtx.getContents({
					success: res => {
						console.log(res);
					}
				})
				this.uploadImage()
			},
			ipt(e) {
				this.artObj.content = e.detail.text || ""
			},
			// 编辑器初始化完成时触发
			onEditorReady() {
				uni.createSelectorQuery().select('.myEdit').context((res) => {
					this.editorCtx = res.context
				}).exec()
			},
			// 改变编辑器内样式时触发
			onStatusChange(e) {
				const formats = e.detail
				this.formats = formats
			},
			// 失焦
			onFocus() {
				this.toolShow = true
			},
			// 提交
			async onSubmit() {
				if (this.getFilesLen() > 3) {
					console.log("图片最多3张");
					return
				}
				await this.uploadImage()
				this.editorCtx.getContents({
					success: res => {
						this.artObj.description = res.text.slice(0, 80);
						this.artObj.content = res.html;
						this.artObj.picurls = getImgSrc(res.html)
						this.processing(this.methodName);
					}
				})
			},
			async processing(methodName) {
				uni.showLoading({
					title: "上传中请稍后",
					mask: true
				})
				let addData = () => {
					return db.collection("cloud_fishCircle-article").add({
						...this.artObj
					})
				}
				let updateData = () => {
					return db.collection("cloud_fishCircle-article").doc(this.articleID).update({
						...this.artObj
					})
				}
				const operationMethod = new Promise((resolve, reject) => {
					if (methodName === 'add') {
						console.log('add');
						resolve(addData())
					} else if (methodName === 'update') {
						console.log('update');
						resolve(updateData());
					} else {
						reject('Error');
					}
				});
				operationMethod.finally(() => {
					uni.hideLoading()
				}).then(res => {
					uni.showToast({
						title: "上传成功",
						icon: "none"
					})
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/index/index"
						})
					}, 800)
				}).catch(err => {
					uni.showToast({
						title: "上传失败",
						icon: "none"
					})
				})
			},
			// 点击触发更改样式
			format(e) {
				let {
					name,
					value
				} = e.target.dataset
				if (!name) return
				// console.log('format', name, value)
				this.editorCtx.format(name, value)
			},
			// 插入分割线
			insertDivider() {
				this.editorCtx.insertDivider()
			},
			// 上传图像
			uploadImage() {
				let newsArr = this.tempFiles.map(async item => {
					// console.log(item);
					return await uniCloud.uploadFile({
						filePath: item["data-local"],
						cloudPath: item.alt
					})
				})
				return Promise.all(newsArr).then(res => {
					console.log(res);
					let newHtml = ""
					let regex = /src="[^"]*".data-local="[^"]*"/
					this.editorCtx.getContents({
						success: (r) => {
							newHtml = r.html;
							res.map(item => {
								newHtml = newHtml.replace(regex, `src="${item.fileID}"`)
							})
							this.editorCtx.setContents({
								html: newHtml
							})
						}
					})
				})
			},
			// 添加图像
			selectImage() {
				uni.chooseImage({
					count: 3,
					success: (res) => {
						// console.log(res);
						res.tempFiles.map(item => {
							// wx没有name属性，随机文件名
							let suffix = item.path.substring(item.path.lastIndexOf("."));
							let randomName = Date.now() + "" + String(Math.random()).substr(3, 6) +
								suffix
							this.editorCtx.insertImage({
								src: item.path,
								alt: item.name || randomName,
								success: function() {
									console.log('insert image success')
								}
							})
						})
					}
				})
			},
			// 获取文件数量
			getFilesLen() {
				this.editorCtx.getContents({
					success: (res) => {
						// console.log(res);
						let {
							ops
						} = res.delta
						let imgTempArr = []
						ops.map(item => {
							// console.log(item);
							try {
								if (item.attributes["data-local"]) {
									imgTempArr.push(item.attributes)
								}
							} catch (e) {
								// 不处理
							}
						})
						this.tempFiles = imgTempArr
						console.log(this.tempFiles);
					}
				})
				return this.tempFiles.length
			},
			// 点击工具条的确认
			editOk() {
				this.toolShow = false;
			},
		}
	}
</script>

<style lang="scss">
	/deep/ .ql-blank::before {
		font-style: normal;
		color: #e0e0e0;
	}

	.edit {
		padding: 30rpx;


		.title {
			input {
				height: 120rpx;
				font-size: 46rpx;
				border-bottom: 1px solid #e4e4e4;
				margin-bottom: 30rpx;
				color: #000;
			}

			.placeholderClass {
				color: #e0e0e0;
			}
		}

		.content {

			.myEdit {
				height: calc(100vh - 500rpx);
				margin-bottom: 30rpx;
			}
		}

		.tools {
			width: 100%;
			height: 80rpx;
			background: #fff;
			border-top: 1rpx solid #f4f4f4;
			position: fixed;
			left: 0;
			bottom: 0;
			display: flex;
			justify-content: space-around;
			align-items: center;

			.iconfont {
				font-size: 36rpx;
				color: #333;

				&.toolsactive {
					color: #0199FE
				}
			}
		}
	}
</style>